<script setup lang="ts">
import { ref, computed } from "vue";
import { invoke } from "@tauri-apps/api/core";

// 响应式数据
const selectedFile = ref<string>("");
const outputDir = ref<string>("");
const filePrefix = ref<string>("split");
const splitType = ref<string>("lines"); // 'lines', 'size' 或 'symbol'
const linesPerFile = ref<number>(1000);
const sizePerFile = ref<number>(10); // MB
const symbolSeparator = ref<string>(""); // 符号分隔符
const symbolItemsPerFile = ref<number>(10); // 符号切割时每个文件包含的数量
const fileInfo = ref<any>(null);
const isProcessing = ref<boolean>(false);
const resultMessage = ref<string>("");
const errorMessage = ref<string>("");

// 计算属性
const canProcess = computed(() => {
  return selectedFile.value && outputDir.value && filePrefix.value && !isProcessing.value;
});

const sizeInBytes = computed(() => {
  return sizePerFile.value * 1024 * 1024; // 转换为字节
});

// 选择文件
async function selectFile() {
  try {
    const result = await invoke<string | null>("select_file");
    if (result) {
      selectedFile.value = result;
      await getFileInfo();
      // 自动设置文件前缀为文件名（不含扩展名）
      const fileName = result.split(/[\\/]/).pop() || "";
      const nameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
      filePrefix.value = nameWithoutExt;
    }
  } catch (error) {
    errorMessage.value = `选择文件失败: ${error}`;
  }
}

// 选择输出目录
async function selectOutputDir() {
  try {
    const result = await invoke<string | null>("select_output_dir");
    if (result) {
      outputDir.value = result;
    }
  } catch (error) {
    errorMessage.value = `选择目录失败: ${error}`;
  }
}

// 获取文件信息
async function getFileInfo() {
  if (!selectedFile.value) return;
  
  try {
    const info = await invoke<any>("get_file_info", { filePath: selectedFile.value });
    fileInfo.value = info;
  } catch (error) {
    errorMessage.value = `获取文件信息失败: ${error}`;
  }
}

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 执行文件分割
async function splitFile() {
  if (!canProcess.value) return;
  
  isProcessing.value = true;
  errorMessage.value = "";
  resultMessage.value = "";
  
  try {
    let result: string = "";
    
    if (splitType.value === "lines") {
      result = await invoke<string>("split_by_lines", {
        filePath: selectedFile.value,
        linesPerFile: linesPerFile.value,
        outputDir: outputDir.value,
        filePrefix: filePrefix.value
      });
    } else if (splitType.value === "size") {
      result = await invoke<string>("split_by_size", {
        filePath: selectedFile.value,
        sizePerFile: sizeInBytes.value,
        outputDir: outputDir.value,
        filePrefix: filePrefix.value
      });
    } else if (splitType.value === "symbol") {
      if (!symbolSeparator.value.trim()) {
        errorMessage.value = "请输入分割符号";
        return;
      }
      result = await invoke<string>("split_by_symbol", {
         filePath: selectedFile.value,
         separator: symbolSeparator.value,
         itemsPerFile: symbolItemsPerFile.value,
         outputDir: outputDir.value,
         filePrefix: filePrefix.value
       });
    }
    
    resultMessage.value = result;
  } catch (error) {
    errorMessage.value = `分割失败: ${error}`;
  } finally {
    isProcessing.value = false;
  }
}

// 清除选择
function clearSelection() {
  selectedFile.value = "";
  outputDir.value = "";
  filePrefix.value = "split";
  fileInfo.value = null;
  resultMessage.value = "";
  errorMessage.value = "";
}
</script>

<template>
  <main class="container">
    <div class="header">
      <h1>📁 文件切割工具</h1>
      <p class="subtitle">快速处理超大文件，支持按行数或大小分割</p>
    </div>

    <!-- 文件选择区域 -->
    <div class="section">
      <h2>📂 选择文件</h2>
      <div class="file-selection">
        <div class="input-group">
          <input 
            v-model="selectedFile" 
            placeholder="请选择要分割的文件" 
            readonly 
            class="file-input"
          />
          <button @click="selectFile" class="btn btn-primary">浏览文件</button>
        </div>
        
        <!-- 文件信息显示 -->
        <div v-if="fileInfo" class="file-info">
          <div class="info-item">
            <span class="label">文件名:</span>
            <span class="value">{{ fileInfo.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">文件大小:</span>
            <span class="value">{{ formatFileSize(fileInfo.size) }}</span>
          </div>
          <div class="info-item">
            <span class="label">行数:</span>
            <span class="value">{{ fileInfo.lines.toLocaleString() }} 行</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输出配置区域 -->
    <div class="section">
      <h2>⚙️ 输出配置</h2>
      <div class="config-grid">
        <div class="config-item">
          <label>输出目录:</label>
          <div class="input-group">
            <input 
              v-model="outputDir" 
              placeholder="选择输出目录" 
              readonly 
              class="dir-input"
            />
            <button @click="selectOutputDir" class="btn btn-secondary">选择目录</button>
          </div>
        </div>
        
        <div class="config-item">
          <label>文件前缀:</label>
          <input 
            v-model="filePrefix" 
            placeholder="输出文件前缀" 
            class="text-input"
          />
        </div>
      </div>
    </div>

    <!-- 分割方式选择 -->
    <div class="section">
      <h2>✂️ 分割方式</h2>
      <div class="split-options">
        <div class="radio-group">
          <label class="radio-option">
            <input 
              type="radio" 
              v-model="splitType" 
              value="lines"
            />
            <span class="radio-label">按行数分割</span>
          </label>
          <label class="radio-option">
            <input 
              type="radio" 
              v-model="splitType" 
              value="size"
            />
            <span class="radio-label">按文件大小分割</span>
          </label>
          <label class="radio-option">
            <input 
              type="radio" 
              v-model="splitType" 
              value="symbol"
            />
            <span class="radio-label">按符号分割</span>
          </label>
        </div>
        
        <div class="split-config">
          <div v-if="splitType === 'lines'" class="config-item">
            <label>每个文件行数:</label>
            <input 
              type="number" 
              v-model="linesPerFile" 
              min="1" 
              class="number-input"
            />
            <span class="unit">行</span>
          </div>
          
          <div v-if="splitType === 'size'" class="config-item">
            <label>每个文件大小:</label>
            <input 
              type="number" 
              v-model="sizePerFile" 
              min="1" 
              step="0.1"
              class="number-input"
            />
            <span class="unit">MB</span>
          </div>
          
          <div v-if="splitType === 'symbol'" class="symbol-config">
             <div class="config-item">
               <label>分割符号:</label>
               <input 
                 type="text" 
                 v-model="symbolSeparator" 
                 placeholder="输入分割符号，如: ===, ---, ###"
                 class="text-input symbol-input"
               />
             </div>
             <div class="config-item">
               <label>每个文件包含数量:</label>
               <input 
                 type="number" 
                 v-model="symbolItemsPerFile" 
                 min="1" 
                 class="number-input"
               />
               <span class="unit">个</span>
             </div>
             <div class="symbol-note">
               <p>💡 提示：遇到指定符号时进行分割，每个文件包含指定数量的内容块</p>
             </div>
           </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="section">
      <div class="action-buttons">
        <button 
          @click="splitFile" 
          :disabled="!canProcess"
          class="btn btn-success btn-large"
        >
          <span v-if="isProcessing">🔄 处理中...</span>
          <span v-else>🚀 开始分割</span>
        </button>
        
        <button 
          @click="clearSelection" 
          class="btn btn-outline"
          :disabled="isProcessing"
        >
          🗑️ 清除
        </button>
      </div>
    </div>

    <!-- 结果显示 -->
    <div v-if="resultMessage || errorMessage" class="section">
      <div v-if="resultMessage" class="result success">
        <h3>✅ 处理完成</h3>
        <p>{{ resultMessage }}</p>
      </div>
      
      <div v-if="errorMessage" class="result error">
        <h3>❌ 处理失败</h3>
        <p>{{ errorMessage }}</p>
      </div>
    </div>
  </main>
</template>

<style scoped>
/* 主容器样式 */
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 15px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 头部样式 */
.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h1 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 2em;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1em;
  margin: 0;
}

/* 区域样式 */
.section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e1e8ed;
}

.section h2 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 1.2em;
  font-weight: 600;
}

/* 输入组样式 */
.input-group {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.file-input,
.dir-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e1e8ed;
  border-radius: 6px;
  font-size: 13px;
  background-color: #f8f9fa;
  color: #495057;
}

.text-input,
.number-input {
  padding: 8px 12px;
  border: 1px solid #e1e8ed;
  border-radius: 6px;
  font-size: 13px;
  transition: border-color 0.3s ease;
}

.text-input:focus,
.number-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #2980b9;
  transform: translateY(-1px);
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #7f8c8d;
  transform: translateY(-1px);
}

.btn-success {
  background-color: #27ae60;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background-color: #229954;
  transform: translateY(-1px);
}

.btn-outline {
  background-color: transparent;
  color: #7f8c8d;
  border: 2px solid #bdc3c7;
}

.btn-outline:hover:not(:disabled) {
  background-color: #ecf0f1;
  border-color: #95a5a6;
}

.btn-large {
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 600;
}

/* 文件信息样式 */
.file-info {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  border-left: 3px solid #3498db;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 600;
  color: #2c3e50;
}

.value {
  color: #7f8c8d;
  font-family: 'Courier New', monospace;
}

/* 配置网格 */
.config-grid {
  display: grid;
  gap: 15px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.config-item label {
  font-weight: 600;
  color: #2c3e50;
  font-size: 13px;
}

/* 单选按钮组 */
.radio-group {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.radio-option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
  transition: all 0.3s ease;
}

.radio-option:hover {
  border-color: #3498db;
  background-color: #f8f9fa;
}

.radio-option input[type="radio"] {
  margin: 0;
}

.radio-label {
  font-weight: 500;
  color: #2c3e50;
}

/* 分割配置 */
.split-config .config-item {
  flex-direction: row;
  align-items: center;
  gap: 10px;
}

.split-config .config-item label {
  min-width: 100px;
}

.split-config .number-input {
  width: 100px;
}

.unit {
  color: #7f8c8d;
  font-weight: 500;
}

/* 符号配置 */
.symbol-config {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e1e8ed;
}

.symbol-config .config-item {
  flex-direction: row;
  align-items: center;
  gap: 10px;
}

.symbol-config .config-item label {
  min-width: 120px;
  font-weight: 600;
  color: #2c3e50;
}

.symbol-input {
  flex: 1;
  min-width: 200px;
}

.symbol-note {
  background-color: #e8f4fd;
  border: 1px solid #bee5eb;
  border-radius: 6px;
  padding: 10px;
}

.symbol-note p {
  margin: 0;
  color: #0c5460;
  font-size: 13px;
  line-height: 1.4;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

/* 结果显示 */
.result {
  padding: 15px;
  border-radius: 6px;
  margin-top: 8px;
}

.result.success {
  background-color: #d5f4e6;
  border-left: 4px solid #27ae60;
}

.result.error {
  background-color: #fdeaea;
  border-left: 4px solid #e74c3c;
}

.result h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.result.success h3 {
  color: #27ae60;
}

.result.error h3 {
  color: #e74c3c;
}

.result p {
  margin: 0;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  
  .section {
    padding: 12px;
  }
  
  .radio-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .input-group {
    flex-direction: column;
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .container {
    background-color: #1a1a1a;
    color: #e1e1e1;
  }
  
  .section {
    background-color: #2d2d2d;
    border-color: #404040;
  }
  
  .header h1,
  .section h2,
  .label {
    color: #e1e1e1;
  }
  
  .subtitle {
    color: #b0b0b0;
  }
  
  .file-input,
  .dir-input {
    background-color: #404040;
    border-color: #555;
    color: #e1e1e1;
  }
  
  .text-input,
  .number-input {
    background-color: #404040;
    border-color: #555;
    color: #e1e1e1;
  }
  
  .file-info {
    background-color: #404040;
  }
  
  .radio-option {
    border-color: #555;
    background-color: #404040;
  }
  
  .radio-option:hover {
    border-color: #3498db;
    background-color: #4a4a4a;
  }
}
</style>